<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button size="mini" type="primary" @click="showDialog=true">添加角色</el-button>
      </div>
      <!-- 放置table组件 -->
      <el-table :data="roleList">
        <!-- 放置列 -->
        <el-table-column prop="name" align="center" width="200" label="角色">
          <template #default="{row}">
            <el-input v-if="row.isEdit" v-model="row.editObj.name" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" width="200" label="启用">
          <template #default="{row}">
            <el-switch v-if="row.isEdit" v-model="row.editObj.state" :active-value="1" :inactive-value="0" size="mini" />
            <span v-else>
              {{ row.state ===1 ? '已启用' :'未启用' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template #default="{row}">
            <el-input v-if="row.isEdit" v-model="row.editObj.description" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template #default="{row}">
            <template v-if="row.isEdit">
              <el-button type="primary" size="mini" @click="btnEditOk(row)">确定</el-button>
              <el-button size="mini" @click="row.isEdit = false">取消</el-button>
            </template>
            <template v-else>
              <el-button type="text" size="mini" @click="assignPer(row.id)">分配权限</el-button>
              <el-button type="text" size="mini" @click="btnEditRow(row)">编辑</el-button>
              <el-popconfirm
                title="这是一段内容确定删除吗？"
                @confirm="confirmDel(row.id)"
              >
                <el-button slot="reference" style="margin-left:10px" type="text" size="mini">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 放置分页组件 -->
      <el-row type="flex" style="height:60px" align="middle" justify="end">
        <!-- 放置分页组件 -->
        <el-pagination
          :current-page="queryData.page"
          :page-sizes="[2, 5, 10, 20]"
          :page-size="queryData.pagesize"
          layout="prev, pager, next"
          :total="total"
          @current-change="handleCurrentChange"
        />
      </el-row>

      <!-- 新增或者编辑的弹层 -->
      <el-dialog
        width="500px"
        :visible.sync="showDialog"
        title="新增或编辑角色"
        @close="close"
      >
        <!-- 表单内容 -->
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
          <el-form-item prop="name" label="角色名称">
            <el-input v-model="roleForm.name" style="width:300px" size="mini" />
          </el-form-item>
          <el-form-item label="启用">
            <!-- 如果不需要校验 就不需要写 prop属性 -->
            <!-- :active-value="1"     指定激活时的值 默认true
                :inactive-value="0"  指定失活的时的值 默认是false
             -->
            <el-switch v-model="roleForm.state" :active-value="1" :inactive-value="0" size="mini" />
          </el-form-item>
          <el-form-item prop="description" label="角色描述">
            <el-input v-model="roleForm.description" type="textarea" :rows="3" style="width:300px" size="mini" />
          </el-form-item>

          <el-form-item>
            <el-row type="flex" justify="center">
              <el-col :span="12">
                <el-button type="primary" size="mini" @click="submit">确定</el-button>
                <el-button size="mini">取消</el-button>
              </el-col>
            </el-row>
          </el-form-item>
        </el-form>
      </el-dialog>

      <!-- 分配权限的弹层 -->
      <el-dialog title="分配权限" :visible.sync="showPerDialog">
        <!--  show-checkbox在el-tree中的节点显示复选框
        default-checked-keys 默认勾选的节点的 key 的数组 需要配合 node-key="id"一起使用
         check-strictly 取消复选框父子关联
         -->
        <el-tree
          ref="tree"
          check-strictly
          node-key="id"
          :default-checked-keys="permIds"
          :data="treePerList"
          :props="{label:'name'}"
          show-checkbox
        />
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button type="primary" size="mini" @click="assignPermission">确定</el-button>
            <el-button size="mini" @click="showPerDialog = false">取消</el-button>
          </el-col>
        </el-row>
      </el-dialog>
    </div>

  </div>
</template>
<script>
import { getRoles, addRole, updateRole, delRole, getRolesDetail, assignRolePermission } from '@/api/role'
import { getPermissionList } from '@/api/permission'
import { transListToTreeData } from '@/utils'
export default {
  name: 'Role',
  data() {
    return {
      permIds: [], // 角色拥有的权限的id的列表
      currenId: null,
      treePerList: [], // 存放权限的树形结构的数据
      showPerDialog: false, // 控制分配权限的弹层
      roleForm: {
        name: '',
        description: '',
        state: 0 // 默认未1启用 关闭 0 打开1
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      },

      showDialog: false,
      roleList: [],
      queryData: {
        page: 1,
        pagesize: 2
      },
      total: 0
    }
  },
  created() {
    this.initData()
  },
  methods: {
    // 实现分配权限
    async assignPermission() {
      //  this.$refs.tree.getCheckedKeys() 获取树组件选中的节点
      await assignRolePermission({ id: this.currenId, permIds:
      this.$refs.tree.getCheckedKeys() })
      this.$message.success('分配权限成功')
      this.showPerDialog = false
    },
    async assignPer(id) {
      this.treePerList = transListToTreeData(
        await getPermissionList(), 0)
      const { permIds } = await getRolesDetail(id)
      this.permIds = permIds
      this.currenId = id
      this.showPerDialog = true
    },
    close() {
      this.roleForm = {
        name: '',
        description: '',
        state: 0 // 默认未1启用 关闭 0 打开1
      }
      this.$refs.roleForm.clearValidate()
    },
    submit() {
      this.$refs.roleForm.validate(async(isOk) => {
        if (!isOk) return // 检验未通过
        await addRole(this.roleForm)
        this.$message.success('新增成功')
        this.showDialog = false
        // 重置表单，重置数据
        this.initData()
      })
    },
    // 当前的页码值改变，实现翻页
    handleCurrentChange(val) {
      this.queryData.page = val
      this.initData()
    },
    async initData() {
      const res = await getRoles(this.queryData)
      console.log(res, 'getRoles')
      this.roleList = res.rows
      this.total = res.total
      this.roleList.forEach(item => {
        // vue中data函数的数据默认是响应式的  数据改变---》视图改变
        // 动态添加的数据 isEdit 是后来动态添加，所以没有被劫持，所以不是响应式
        // item.isEdit = false
        // vue中可以使用  this.$set(目标对象,属性名，值) 或  Vue.set()  将动态添加属性变成响应式的的数据
        this.$set(item, 'isEdit', false)
        // 给表单填充数据，添加缓存对象的数据
        this.$set(item, 'editObj', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
    },
    btnEditRow(row) {
      row.isEdit = true
      row.editObj.name = row.name
      row.editObj.state = row.state
      row.editObj.description = row.description
    },
    async btnEditOk(row) {
      if (row.editObj.name && row.editObj.description) {
        // 检验通过，发送请求
        await updateRole({ ...row.editObj, id: row.id })
        this.$message.success('更新角色成功！')
        // row.isEdit = false // eslint校验的问题 失误
        // Object.assign(target,source)
        // {isEdit:true}   {isEdit: false}
        Object.assign(row, {
          // 将表单里面的新数据row.editObj，更新到表格中 row
          ...row.editObj,
          isEdit: false
        })
      } else {
        this.$message.error('角色名称或角色的描述不能为空！')
      }
    },
    async confirmDel(id) {
      console.log(id, 'id')
      // 发送请求，实现删除
      await delRole(id)
      this.$message.success('删除角色成功！')
      // 如果有分页功能，需要判断是否是页面最后一条数据，如果是，需要将页码值减1
      // 页码值不能一直减，如果小于1，那么需要将page直接改1
      if (this.roleList.length === 1) {
        this.queryData.page--
        // if (this.queryData.page < 1) {
        //   this.queryData.page = 1
        // }
      }
      // 更新数据
      this.initData()
    }
  }
}
</script>

<style scoped lang="scss">
.role-operate {
  padding: 10px;
}
</style>
